require("plugin")

plugin.photo = {
	new = function(owner)
		local self = { plugin = owner }
		setmetatable(self, { __index = plugin.photo })
		return self
	end,
	
	activate = function(self)
		self:showPage()
	end,
	
	deactivate = function(self)
	end,
	
	check = function(self)
		self.plugin.stoicheia:checkCmd(0, "exif", "--usage")
	end,
	
	filter = function(path, dir)
		if dir then return true end
		return common.suffixFilter(path, "jpg", "jpeg", "gif", "png")
	end,
	
	showPage = function(self)
		self.plugin.stoicheia:showPage("photo", function(event, f)
			if event ~= "html" then return end
			local dir = string.format("%s/photo", common.getConfig("path.user.datadir"))
			self.tree = common.tree(dir, true)
			local w, h = self.plugin.stoicheia:getScreenSize()
			f:beginList(100, 200, w - 450, h - 300)
			self.pathids = {}
			self.nodeids = {}
			common.traverse(self.tree, function(node, name, depth, leaf, path, leafcount, childcount)
				if name == nil then name = common.getResource("root") end
				if leaf then return end
				if childcount == 0 then return end
				local notify, title = nil, name
				if leafcount > 0 then
					local id = #self.pathids + 1
					self.pathids[id] = path
					self.nodeids[id] = node
					notify = id
					title = string.format("%s (%d)", name, leafcount)
				end
				f:renderListItem(title, notify, depth * 2)
			end, dir, self.filter)
			f:endList()
		end)
		self.plugin.stoicheia:setControls(true, "back")
	end,
	
	showImagePage = function(self)
		local f = form.new("photo2", "xhtml")
		local width, height = self.plugin.stoicheia:getScreenSize()
		f.r:xmlHeader("UTF-8")
		f.r:beginl("html", { xmlns = "http://www.w3.org/1999/xhtml" })
		f.r:beginl("head")
		f:script(nil, [[
			function notify(event){
				window.status = "VALUE " + event;
			}
			function setImage(url){
				var image = document.getElementById("image");
				image.src = url;
			}
			function setLabel(value){
				var label = document.getElementById("label");
				label.innerText = value;
			}
		]])
		f.r:beginl("style")
		f.r:cssSheet({
			body = {
				margin = "0px",
				padding = "0px"
			},
			[".frame"] = {
				position = "absolute",
				left = "0px",
				top = "0px",
				width = width .. "px",
				height = height .. "px",
				overflow = "hidden",
				["background-color"] = "#000000"
			},
			["#image"] = {
				["max-width"] = width .. "px",
				["max-height"] = height .. "px"
			},
			[".label-envelope"] = {
				position = "absolute",
				right = "40px",
				bottom = "40px"
			},
			["#label"] = {
				color = "#ffffff",
				["font-family"] = f.fontFamily,
				["font-size"] = f.fontSize .. "px"
			}
		})
		f:renderRoundRectCss("roundrect", 6, "roundrect")
		f.r:endl("style")
		f.r:endl("head")
		f.r:beginl("body", {
			onload = "notify('PAGE');"
		})
		f.r:beginl("table", {
			class = "frame",
			cellpadding = 0,
			cellspacing = 0
		})
		f.r:beginl("tr")
		f.r:beginl("td", {
			align = "center",
			valign = "center"
		})
		f.r:emptyl("img", {
			id = "image",
			onload = "notify('IMAGE');"
		})
		f.r:endl("td")
		f.r:endl("tr")
		f.r:endl("table")
		f.r:htmlDivBegin("label-envelope")
		f:beginRoundRect("roundrect")
		f.r:htmlDiv(nil, { id = "label" })
		f:endRoundRect("roundrect")
		f.r:htmlDivEnd("label-envelope")
		f.r:endl("body")
		f.r:endl("html")
		f:close()
		self.plugin.stoicheia:open(f.path)
		self.plugin.stoicheia:setControls(false, "back", "previous", "next")
	end,
	
	controlEvent = function(self, event)
		if event == "back" then
			if self.currentPath ~= nil then
				self.currentPath = nil
				self.currentPhotos = nil
				self.currentIndex = nil
				self:showPage()
			else
				self.plugin.stoicheia:showStartPage()
			end
			return
		end
		if event == "next" then
			if self.currentIndex < #(self.currentPhotos) then
				self.currentIndex = self.currentIndex + 1
				self:refresh()
			end
			return
		end
		if event == "previous" then
			if self.currentIndex > 1 then
				self.currentIndex = self.currentIndex - 1
				self:refresh()
			end
			return
		end
		log("plugin.photo", "Unknown photo control `%s'", event)
	end,
	
	pageEvent = function(self, event, arg)
		if event == "CLICKED" then
			local id = tonumber(arg)
			local node = self.nodeids[id]
			self.currentPath = self.pathids[id]
			self.currentPhotos = {}
			common.traverse(node, function(node, name, depth, leaf, path, leafcount)
				if not leaf then return end
				if depth ~= 1 then return end
				self.currentPhotos[#self.currentPhotos + 1] = name
			end, self.currentPath, self.filter)
			self.currentIndex = 1
			self:showImagePage()
			self:refresh()
			return
		end
		if event == "VALUE" then
			if arg == "PAGE" then
				self:refresh()
			end
			return
		end
	end,
	
	refresh = function(self)
		local path = self.currentPath .. "/" .. self.currentPhotos[self.currentIndex]
		self:exec(string.format("setImage(%q);", "file://" .. path))
		local label = string.format("(%d. %s %d) ", self.currentIndex, common.getResource("of"), #(self.currentPhotos))
		local date = self:getDate(path)
		if date ~= nil then label = label .. " " .. date end
		self:exec(string.format("setLabel(%q);", label))
	end,
	
	exec = function(self, code)
		self.plugin.stoicheia.gui.pagewin:exec(code)
	end,
	
	exif = function(self, path)
		local ret = {}
		local f = task.executer("exif", "-i", path)
		for line in f:lines() do
			if line:indexof("|") then
				local segs = line:split("|")
				if #segs == 2 then
					local name = segs[1]:trim()
					local value =segs[2]:trim()
					if name ~= "Tag" then
						ret[name] = value
					end
				end
			end
		end
		f:close()
		return ret
	end,
	
	getDate = function(self, path)
		local dateids = { "0x0132", "0x9003", "0x9004" }
		local values = self:exif(path)
		for i, id in ipairs(dateids) do
			local value = values[id]
			if value ~= nil then
				value = value:gsub("(%d%d%d%d):(%d%d):(%d%d)", function(year, month, day)
					local mi = tonumber(month)
					local ms = common.getResource("month." .. month)
					return string.format("%s/%s/%s", year, ms, day)
				end)
				return value
			end
		end
	end
}


